package com.study.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.date.DateStringConverter;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

public class EasyExcelUtils {

    //public static <T> List<T> readExcel(MultipartFile file, Class<T> clazz, Integer headRowNumber) throws IOException {
    //    List<T> list = null;
    //    return list;
    //}

    // 导出excel
    public static  <T> void exportExcel(List<T> dataList, Class<T> clazz, String fileName, String sheetName, HttpServletResponse response) throws IOException {
        setResponseHeader(response, fileName);
        EasyExcel.write(response.getOutputStream())
                .head(clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .registerConverter(new DateStringConverter())
                .sheet(sheetName)
                .doWrite(dataList);
    }

    // 设置导出Excel的响应头
    public static void setResponseHeader(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
    }

}
